<?php
function getConnection()
{
  $dbhost = 'localhost'; // 更改为 localhost 或 127.0.0.1
  $dbuser = 'root'; // 请替换为您的用户名
  $dbpass = '123456'; // 请替换为您的密码
  $dbname = 'test_db';   // 请替换为您的数据库名

  // 更改 root 用户的认证方法为 mysql_native_password
  $alterUserSql = "ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '123456';";
  $flushPrivilegesSql = "FLUSH PRIVILEGES;";

  $conn = new mysqli($dbhost, $dbuser, $dbpass);
  if ($conn->connect_error) {
    die('连接失败： ' . $conn->connect_error);
  }

  // 执行 SQL 语句以更改认证方法
  $conn->query($alterUserSql);
  $conn->query($flushPrivilegesSql);

  $conn->close(); // 关闭连接

  // 重新连接
  $dbh = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8", $dbuser, $dbpass, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
  ]);

  return $dbh;
}

/**
 * 将参数变为字符串
 * @param $array_query
 * @return string
 */
function getUrlQuery($array_query)
{
  $tmp = [];
  foreach ($array_query as $k => $param) {
    $tmp[] = $k . '=' . urlencode($param);
  }
  $params = implode('&', $tmp);
  return $params;
}

$url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

$arr = parse_url($url);
parse_str($arr['query'], $arr_query);

// 确保 'p' 和 'type' 已设置并且有有效的值
if (!isset($arr_query['p'])) {
  $arr_query['p'] = 1;
}
if (!isset($arr_query['type'])) {
  $arr_query['type'] = 0;
}
$arr_query['p'] = (int)$arr_query['p'];
$arr_query['type'] = (int)$arr_query['type'];

$categorys = [
  1 => '清纯美女',
  2 => '唯美写真',
  3 => '性感美女',
  4 => '明星美女',
  5 => '丝袜美女',
  6 => '美女模特'
];

$condition = '';
if ($arr_query['type'] > 0 && array_key_exists($arr_query['type'], $categorys)) {
  $condition = 'WHERE category = "' . $categorys[$arr_query['type']] . '"';
}

$sql = "SELECT id, addtime, image, content, name, category FROM girls " . $condition . " ORDER BY id ASC LIMIT " . (($arr_query['p'] - 1) * 10) . ", 10";

try {
  $db = getConnection();
  $stmt = $db->prepare($sql);
  $stmt->execute();
  $results = $stmt->fetchAll();
  echo '{"girls": ' . json_encode($results) . '}';
} catch (PDOException $e) {
  echo '{"error": {"text": "' . $e->getMessage() . '"}}';
}
